#include "serialport.h"
#include "wiringPi.h"
#include "wiringSerial.h"

#include <QDebug>
#include "cirbuff.h"

SerialPort::SerialPort(QThread *parent)
    : QThread(parent){}

SerialPort::~SerialPort(){}

bool SerialPort::openSerial()
{
    m_isExit = false;
    usart_fd = serialOpen("/dev/ttyAMA0",115200);
    this->start();
    if(usart_fd < 0)
    {
        return false;
    }

    return true;
}

void SerialPort::closeSerial()
{
    m_isExit = true;
    serialClose(usart_fd);
    this->exit();
}

void SerialPort::sendData(quint8 c)
{
    serialPutchar(usart_fd, c);
}

void SerialPort::sendString(const QByteArray &ba)
{
    qDebug() << "Send: " << ba.toHex();
    for(int i = 0; i < ba.length(); i++)
    {
        serialPutchar(usart_fd, ba.at(i));
    }
}

void SerialPort::run()
{
    quint8 byte;
    int len = 0;
    QByteArray array;
    qDebug() << "SerialPort::run()";
    while(!m_isExit)
    {
        array.clear();
        len = serialDataAvail(usart_fd);
        if(len > 0)
        {
            for(int i = 0; i < len; i++)
            {
                byte = serialGetchar(usart_fd);
                CirBuff::writeByte(byte);
                array.append(byte);
            }
            emit signalReadyRead(array);
        }
        msleep(2);
    }
}
